package com.ctl.client;

import com.ctl.config.ServerConfig;
import com.ctl.constants.NettyConstants;
import com.ctl.server.NettyServer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ServiceConfigurationError;

/**
 * @author Gjing
 **/
@Slf4j
@Component
public class NettyClient {
    @Value("${netty.address}")
    private String hostname;
    @Value("${netty.port:8090}")
    private Integer port;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private NettyClientInitializer nettyClientInitializer;
    public static long clientCountUid = System.currentTimeMillis();

    public void start() {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                //该参数的作用就是禁止使用Nagle算法，使用于小数据即时传输
                .option(ChannelOption.TCP_NODELAY, true)
                .channel(NioSocketChannel.class)
                .handler(nettyClientInitializer);

        try {
            ChannelFuture future = bootstrap.connect(hostname, port).sync();
            Long increment = redisTemplate.opsForValue().increment(NettyConstants.CLIENT_ID_PRE + clientCountUid);
            log.info("客户端{}成功....", increment);
            //发送消息
            future.channel().writeAndFlush("第" + increment + "个客户端报道");
            // 等待连接被关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("", e);
        } finally {
            log.info("客户端over");
            group.shutdownGracefully();
        }
    }
}
